export function mapMenusToPermission(userMenus) {
  const permissions = [];

  const _recurseGetPermission = (menus) => {
    for (const menu of menus) {
      if (menu.type === 1 || menus.type === 2) {
        _recurseGetPermission(menu.children ?? []);
      } else {
        permissions.push(menu.permissions);
      }
    }
  };

  _recurseGetPermission(userMenus);
  return permissions;
}

export function mapMenusToRoutes(userMenus) {
  const routes = [];

  const allRoutes = [];
  const routeFiles = require.context("../router/main", true, /\.js/);
  routeFiles.keys().forEach((key) => {
    const route = require("../router/main" + key.split(".")[1]);
    allRoutes.push(route.defalut);
  });

  const _recuresGetRoute = (menus) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url);
        if (route) routes.push(route);
      } else {
        _recuresGetRoute(menu.children);
      }
    }
  };

  _recuresGetRoute(userMenus);
  return routes;
}

export function pathMaoBreadcrumbs(userMenus, currentPath) {
  const breadcrumbs = [];
  pathMapToMenu(userMenus, currentPath, breadcrumbs);
  return breadcrumbs;
}

export function pathMapToMenu(userMenus, currentPath, breadcrumbs) {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath);
      if (findMenu) {
        breadcrumbs.push({ name: menu.name });
        breadcrumbs.push({ name: findMenu.name });
        return findMenu;
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu;
    }
  }
}

export function getMenuLeafKeys(menuList) {
  const leftKeys = [];

  const _recuresGetLeaf = (menuList) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recuresGetLeaf(menu.children);
      } else {
        leftKeys.push(menu.id);
      }
    }
  };

  _recuresGetLeaf(menuList);
  return leftKeys;
}
